package one.bugu.android.demon.ui.widget;

import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.*;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.CountDownTimer;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.PathInterpolator;
import android.view.animation.TranslateAnimation;

import com.juefeng.android.framework.common.util.StringUtil;

import one.bugu.android.demon.R;
import one.bugu.android.demon.ui.refresh.util.DensityUtil;
import one.bugu.android.demon.util.ColorUtil;
import one.bugu.android.demon.util.DateUtils;
import one.bugu.android.demon.util.TimerTaskUtils;

/**
 * Created with IntelliJ IDEA.
 * User: LangK
 * Created Date 2018/9/19
 * Time: 13:52
 * Description: 布谷粒视图
 */
public class DropView extends View {

    /**
     * 画笔
     */
    private Paint mPaint;

    /**
     * 圆形图片的半径
     */
    private String text;

    /**
     * 字体大小
     */
    private float textSize;
    /**
     * 图片大小
     */
    private float imageSize;

    public static final String TIME_COUNT = " ";

    private OnHideListener onHideListener;
    private CountDownTimer countDownTimer;

    public DropView(Context context, String text) {
        super(context);
        this.text = text;
        //判断如果此时没有可收集的BGT, 此时显示倒计时
        if (TextUtils.equals(TIME_COUNT, text)) {
            //倒计时
            long farmCountTime = DateUtils.getFarmCountTime();
            if (countDownTimer != null) {
                countDownTimer.cancel();
            }
            countDownTimer = new CountDownTimer(farmCountTime * 1000, 1000) {
                @Override
                public void onTick(long millisUntilFinished) {
                    DropView.this.text = "仅剩 " + DateUtils.secToTime(millisUntilFinished) + "领取";
                    invalidate();
                }
                @Override
                public void onFinish() {
                    DropView.this.text = "正在生长中";
                    if (onRefrushListener != null) {
                        onRefrushListener.refrushData();
                    }
                    invalidate();
                }
            }.start();
        } else {
            if (countDownTimer != null) {
                countDownTimer.cancel();
            }
        }
        initView();
    }

    public DropView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
        initView();
    }

    public DropView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray ta = getContext().obtainStyledAttributes(attrs, R.styleable.DropView);
        String text = ta.getString(R.styleable.DropView_text);
        if (!StringUtil.isEmpty(text)) {
            this.text = text;
        }
        initView();
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public DropView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        TypedArray ta = getContext().obtainStyledAttributes(attrs, R.styleable.DropView);
        String text = ta.getString(R.styleable.DropView_text);
        if (!StringUtil.isEmpty(text)) {
            this.text = text;
        }
        initView();
    }

    private void initView() {
        textSize = DensityUtil.sp2px(12);
        imageSize = DensityUtil.dp2px(32);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (StringUtil.isEmpty(text)) {
            return;
        }
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        float width = getMeasuredWidth();
        float height = getMeasuredHeight();
        int imageLeft = (int) ((width - imageSize) / 2);
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.nongchang_bgt_big);
        float mScale = imageSize / Math.min(bitmap.getHeight(), bitmap.getWidth());
        Matrix matrix = new Matrix();
        matrix.setScale(mScale, mScale);
        BitmapShader bitmapShader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
        bitmapShader.setLocalMatrix(matrix);
        mPaint.setShader(bitmapShader);
        //canvas画一个圆 使用设置了shader的paint
        canvas.drawBitmap(bitmap, imageLeft, 0, mPaint);
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setColor(ColorUtil.getColor(getContext(), R.color.font_white));
        mPaint.setStrokeWidth(3);
        mPaint.setTextSize(textSize);
        Rect rect = new Rect();
        mPaint.getTextBounds(text, 0, text.length(), rect);
        float textWidth = rect.width();
        float textHeight = rect.height();
        float x = (width - textWidth) / 2;
        float y = height - textHeight / 2;
        //无bgt时
        if (text.contains("仅剩") || text.contains("正在生长中")) {
            y = (height - textHeight) / 2 + 10;
        }
        canvas.drawText(text, x, y, mPaint);
    }


    private TranslateAnimation downAction;

    /**
     * 开始动画
     */
    public void startAnimation() {
        downAction = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
                Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
                0.0f, Animation.RELATIVE_TO_SELF, 0.2f);
        downAction.setDuration(1000);
        downAction.setRepeatCount(Animation.INFINITE);
        downAction.setRepeatMode(Animation.REVERSE);
        startAnimation(downAction);
    }

    public void hide(float x, float y) {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
            Path path = new Path();
            float viewX = getX();
            float viewY = getY();
            float controlX = Math.abs(viewX - x);
            float controlY = Math.abs(viewY - y);
            controlX = ((float) Math.random() * controlX);
            controlY = ((float) Math.random() * controlY);
            if (controlX > x * 2 / 3) {
                controlX = x * 2 / 3;
            }
            path.moveTo(viewX, viewY);
            path.quadTo(controlX, controlY, x, y);

            PathInterpolator pathInterpolator = null;
            pathInterpolator = new PathInterpolator(0.33f, 0f, 0.12f, 1f);
            AnimatorSet animSet = new AnimatorSet();
            animSet.addListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationStart(Animator animation) {
                }

                @Override
                public void onAnimationEnd(Animator animation) {
                    if (downAction != null) {
                        downAction.cancel();
                        downAction = null;
                    }
                    clearAnimation();
                    setVisibility(View.GONE);
                    if (onHideListener != null) {
                        onHideListener.removed(DropView.this);
                    }
                }

                @Override
                public void onAnimationCancel(Animator animation) {

                }

                @Override
                public void onAnimationRepeat(Animator animation) {
                }
            });
            ObjectAnimator scalex = ObjectAnimator.ofFloat(this, View.SCALE_X, 1.0f, 0.1f);
            ObjectAnimator scaley = ObjectAnimator.ofFloat(this, View.SCALE_Y, 1.0f, 0.1f);
            ObjectAnimator traslateAnimator = ObjectAnimator.ofFloat(this, "x", "y", path);
            animSet.playTogether(scalex, scaley, traslateAnimator);
            animSet.setInterpolator(pathInterpolator);
            animSet.setDuration(1000);
            animSet.start();
        } else {
            setVisibility(View.GONE);
            if (onHideListener != null) {
                onHideListener.removed(DropView.this);
            }
        }

    }

    public OnHideListener getOnHideListener() {
        return onHideListener;
    }

    public void setOnHideListener(OnHideListener onHideListener) {
        this.onHideListener = onHideListener;
    }

    public interface OnHideListener {
        void removed(View view);


    }

    public OnRefrushListener onRefrushListener;

    public void setOnRefrushListener(OnRefrushListener onRefrushListener) {
        this.onRefrushListener = onRefrushListener;
    }

    public interface OnRefrushListener {
        void refrushData();
    }
}
